package suncertify.gui.dialogs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 * This class provides a JDialog that closes when the escape key is pressed. This class extends the {@link JDialog} and
 * overrides the <code>createRootPane()</code> function.
 * 
 */
public class JEscapeKeyDialog extends JDialog {

    /**
     * Automatically generated serialization version ID.
     */
    private static final long serialVersionUID = -4696967336765642854L;

    /**
     * Constructs the class by calling the <code>super();</code>.
     */
    public JEscapeKeyDialog() {

	super();
    }

    /**
     * Creates the dialog's root pane. This function creates a {@link KeyStroke} for the {@link KeyEvent#VK_ESCAPE} that
     * corresponds to the 'escape' key in Microsoft Windows operation system, the key stroke event is registered in the
     * root pane object. The {@link ActionListener} for the escape key is an instance of the
     * {@link EscapeKeyStrokeActionListener}.
     * 
     * @return The dialogs root pane.
     * 
     */
    protected JRootPane createRootPane() {

	KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);

	JRootPane rootPane = new JRootPane();

	rootPane.registerKeyboardAction(new EscapeKeyStrokeActionListener(), keyStroke,
		JComponent.WHEN_IN_FOCUSED_WINDOW);

	return rootPane;
    }

    /**
     * Provides an implementation for the {@link ActionListener} interface. This class provides the
     * {@link ActionListener#actionPerformed(ActionEvent)} implementation for the escape key click in the
     * {@link JDialog} root pane.
     * 
     */
    private class EscapeKeyStrokeActionListener implements ActionListener {

	/**
	 * Sets the visibility of the {@link JDialog} to false by calling {@link JDialog#setVisible(boolean)}.
	 * 
	 * @param actionEvent
	 *            See {@link ActionEvent}. This parameter is not used in this function.
	 * 
	 */
	public void actionPerformed(ActionEvent actionEvent) {
	    setVisible(false);
	}
    }
}
